package controllers.participant;

import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.encoding.Md5PasswordEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import security.UserAccount;
import services.ParticipantService;
import controllers.AbstractController;
import domain.Participant;

@Controller
@RequestMapping("/security/registration")
public class RegisterParticipantController extends AbstractController {
	@Autowired
	private ParticipantService participantService;

	@RequestMapping(value = "/participant", method = RequestMethod.GET)
	public ModelAndView registration() {
		ModelAndView result;
		Participant participant;

		participant = participantService.create();

		result = createEditModelAndView(participant);

		return result;
	}

	protected ModelAndView createEditModelAndView(Participant participant) {
		ModelAndView result;

		result = createEditModelAndView(participant, null);

		return result;
	}

	protected ModelAndView createEditModelAndView(Participant participant,
			String message) {
		ModelAndView result;

		result = new ModelAndView("security/registration/participant");

		result.addObject("participant", participant);
		result.addObject("authority", "participant");
		result.addObject("message", message);

		return result;
	}

	@RequestMapping(value = "/participant", method = RequestMethod.POST, params = "save")
	public ModelAndView save(@Valid Participant participant,
			BindingResult binding) {
		ModelAndView result;

		if (binding.hasErrors()) {
			result = createEditModelAndView(participant);
		} else {
			try {
				Md5PasswordEncoder encoder = new Md5PasswordEncoder();
				UserAccount user = participant.getUserAccount();
				String password = user.getPassword();
				String hash = encoder.encodePassword(password, null);
				user.setPassword(hash);
				participant.setUserAccount(user);
				participantService.save(participant);
				result = new ModelAndView("redirect:../../");

			} catch (Throwable oops) {

				result = createEditModelAndView(participant,
						"participant.commit.error");
			}
		}

		return result;
	}
}
